import express from 'express'
import sqlQuery from '../utils/sql';
import { getTime } from '../utils/decodeTime';
const router = express.Router()
// 获取用户
router.post('/getUserInfo', async (requset, reponese) => {
    let {
        phone
    } = requset.body
    let res = await sqlQuery(`select * from user where phone = '${phone}'`)
    reponese.send(res)
})
// 修改用户信息
router.post('/editUser', async (requset, reponese) => {
    let {
        uid,
        user
    } = requset.body
    await sqlQuery(`update user set name = '${user}' where uid = '${uid}'`)
    reponese.send('修改成功')
})

// 密码登录 比对账号和密码
router.post('/compareUser', async (requset, reponese) => {
    let {
        password,
        username
    } = requset.body
    let res = await sqlQuery(`select * from user where password = '${password}'  and name = '${username}'`)
    if (res.length === 1) {
        reponese.send(res)
    } else {
        reponese.send({
            code: 404,
            msg: 'error'
        })
    }

})
// 修改密码 
router.post('/Editpass', async (requset, reponese) => {
    let {
        phone,
        password
    } = requset.body
    let res = await sqlQuery(`update user set password = '${password}'  where phone = '${phone}'`)
    if (res.changedRows === 1) {
        reponese.send({
            code: 200
        })
    } else {
        reponese.send({
            code: 404
        })
    }
})
// 添加用户
router.post('/addUser', async (requset, responese) => {
    let {
        phone,
        password,
        name,
        sex,
        birthday
    } = requset.body
    console.log(birthday);
    const uid = await sqlQuery('select * from user')
    const length = uid.length
    let res = await sqlQuery(`insert into user values('u${length + 1}','${name}','${phone}','${birthday}','${sex}',0,null,'2',null,'${password}')`)
    if (res.affectedRows === 1) {
        responese.send({
            code: 200,
            msg: '成功'
        })
    } else {
        responese.send({
            code: '404',
            msg: '添加失败 服务器寄了'
        })
    }
})
module.exports = router
//修改用户积分// 添加优惠券
router.post('/editIntegral',async (requset,reponese)=>{
    const  {name,price,img,integral,uid,coid,type} = requset.body

    const coupons = await sqlQuery(`select coupons from user where uid = '${uid}'`)
    const num = coupons[0].coupons

    let change1 = await sqlQuery(`update user set integral = '${integral *1 - price * 1}',coupons = '${num * 1 + 1}' where uid = '${uid}' `)
    let change2 = await sqlQuery(` insert into coupons  values ('${name}','${uid}',null,'${coid}','${type}')  `)
    if(change1.affectedRows === 1 && change2.affectedRows === 1){
        reponese.send({
            code: 200
        })
    } else {
        reponese.send({
            code: 404
        })
    }
})


module.exports = router  
